const vscode = require('vscode');
const path = require('path');
const { exec } = require('child_process');
const fs = require('fs');
const stringify = require('json-stable-stringify-without-jsonify');

function get_lua_exe_path(command, args) {
    const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;

    const cmd = []
    const parentDir = path.dirname(__dirname);
    cmd.push(path.join(parentDir, 'plugin\\CLua.exe'));
    cmd.push(`"${command}"`);
    cmd.push(`"${workspaceFolder}"`);

    if (args != null) {
        args.forEach(element => {
            cmd.push(element);
        });
    }

    return cmd
}


// 创建自定义输出通道
const War3Helper = vscode.window.createOutputChannel('war3helper', {
    log: true,
});


async function run_lua(command, args) {
    const cmd = get_lua_exe_path(command, args);

    // 设置当前工作目录为 CLua.exe 所在的目录
    const options = {
        encoding: 'utf8',
        cwd: vscode.workspace.workspaceFolders[0].uri.fsPath // 设置工作目录为当前工作区根目录
    };

    return new Promise((resolve, reject) => {
        exec(cmd.join(" "), options, (error, stdout, stderr) => {
            if (error) {
                War3Helper.error(error);
                War3Helper.hide();
                War3Helper.show();
                reject(error);
            } else {
                if (stdout.length > 0) {
                    War3Helper.info(stdout.trimEnd());
                }
                if (stderr.length > 0) {
                    War3Helper.error(stderr.trimEnd());
                }
                War3Helper.hide();
                War3Helper.show();
                resolve();
            }
        });
    });
}

async function cmd_run_lua(fsPath, args) {
    let terminal = vscode.window.terminals.find(t => t.name === 'CLua cmd');

    if (!terminal) {
        terminal = vscode.window.createTerminal({
            name: 'CLua cmd',
            shellPath: "cmd.exe",
            cwd: vscode.workspace.workspaceFolders[0].uri.fsPath // 设置工作目录为当前工作区根目录
        });
    }
    const cmd = get_lua_exe_path(fsPath);
    if (args != null) {
        args.forEach(element => {
            cmd.push(`\"${element}\"`);
        });
    }
    terminal.show();
    terminal.sendText(cmd.join(' '));
}

async function GetWar3Table(key) {
    const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
    const jsonPath = path.join(workspaceFolder, '.vscode', key);

    if (await fs.existsSync(jsonPath)) {
        try {
            const data = await fs.readFileSync(jsonPath, 'utf8');
            const jsonObject = JSON.parse(data);
            return jsonObject;
        } catch (error) {
            War3Helper.error('获取War3Table路径失败!:' + error);
            War3Helper.hide()
            War3Helper.show()
        }
    }

    return null; // 如果文件不存在或读取失败，返回 null 或其他默认值
}

async function SetWar3Table(key, value) {
    const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
    const jsonPath = path.join(workspaceFolder, '.vscode', key);

    await fs.writeFileSync(jsonPath, stringify(value, { space: 4 }), "utf-8")
}

async function SetConfigList(key, input) {
    const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
    const War3Config = path.join(workspaceFolder, '.vscode', 'War3Config.json');

    if (!await fs.existsSync(War3Config)) {
        // 创建默认的 War3Config.json 文件
        const defaultConfig = {
            "窗口化": false,
            "OpenGL": false
        };
        await fs.mkdirSync(path.dirname(War3Config), { recursive: true });
        await fs.writeFileSync(War3Config, stringify(defaultConfig, { space: 4 }), "utf-8");
    }

    try {
        const data = await fs.readFileSync(War3Config, 'utf8');
        const jsonObject = JSON.parse(data);
        jsonObject[key] = input;
        await fs.writeFileSync(War3Config, stringify(jsonObject, { space: 4 }), "utf-8")
    } catch (error) {
        War3Helper.error('获取War3Config路径失败!:' + error);
        War3Helper.hide()
        War3Helper.show()
    }
}

async function UpdateWar3Config() {
    const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
    const War3Config = path.join(workspaceFolder, '.vscode', 'War3Config.json');
    try {
        const data = await fs.readFileSync(War3Config, 'utf8');
        const jsonObject = JSON.parse(data);
        await fs.writeFileSync(War3Config, stringify(jsonObject, { space: 4 }), "utf-8")
    } catch (error) {
        War3Helper.error('获取War3Config路径失败!:' + error);
        War3Helper.hide()
        War3Helper.show()
    }
}

async function GetConfigList(key) {
    const workspaceFolder = vscode.workspace.workspaceFolders[0].uri.fsPath;
    const War3Config = path.join(workspaceFolder, '.vscode', 'War3Config.json');

    if (await fs.existsSync(War3Config)) {
        try {
            const data = await fs.readFileSync(War3Config, 'utf8');
            const jsonObject = JSON.parse(data);
            return jsonObject[key];
        } catch (error) {
            War3Helper.error('获取War3Config路径失败!:' + error);
            War3Helper.hide()
            War3Helper.show()
        }
    }

    return null; // 如果文件不存在或读取失败，返回 null 或其他默认值
}

async function isFileLocked(filePath) {
    if (!await fs.existsSync(filePath))
        return false;
    return new Promise((resolve, reject) => {
        fs.open(filePath, 'r+', (err, fd) => {
            if (err) {
                if (err.code === 'EBUSY') {
                    resolve(true); // 文件被占用
                } else {
                    reject(err); // 其他错误
                }
            } else {
                fs.close(fd, (err) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(false); // 文件未被占用
                    }
                });
            }
        });
    });
}
function isRelativePath(p) {
    // 检查路径是否以'.'或'..'开头
    if (p.startsWith('.') || p.startsWith('..')) {
        return true;
    }
    // 检查路径是否以根目录符号开头
    if (path.isAbsolute(p)) {
        return false;
    }
    return true;
}
async function deleteFile(filePath) {
    if (!await fs.existsSync(filePath))
        return;
    const fullPath = path.resolve(filePath);
    await fs.unlinkSync(fullPath, (err) => {
        if (err) {
            console.error(`删除文件时出错: ${err.message}`);
            return;
        }
        console.log(`文件已成功删除: ${fullPath}`);
    });
}

module.exports = {
    War3Helper,
    run_lua,
    cmd_run_lua,
    UpdateWar3Config,
    GetConfigList,
    SetConfigList,
    GetWar3Table,
    SetWar3Table,
    isFileLocked,
    isRelativePath,
    deleteFile,
}